package remote

import (
	"apedge/pkg/configs"
	"apedge/pkg/loggers"
	"apedge/pkg/protocol"
	"apedge/pkg/utils"
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"github.com/mitchellh/mapstructure"
)

var logger = loggers.LogInstance()

func CreatApflow(reqContent protocol.CreatApflowServiceReq) (*protocol.CreatApflowServiceRsp, error) {
	var creatServiceRsp protocol.CreatApflowServiceRsp
	var client = &http.Client{
		Timeout: time.Second * 10,
	}

	data, err := json.Marshal(reqContent)
	if err != nil {
		return nil, err
	}
	logger.Info("create apflow server req: %s", string(data))

	url := utils.GetHttpUrl(configs.Config.Relevant.Service.InferenceBackendSvc, APFLOW_URL)
	logger.Infoln("apflow-backend url: ", url)

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var respBody protocol.APISuccessRsp
	err = json.NewDecoder(resp.Body).Decode(&respBody)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != 200 {
		return nil, fmt.Errorf("inference-backend create svc error %d %+v", resp.StatusCode, respBody)
	}

	if respBody.Code != 0 {
		return nil, fmt.Errorf("inference-backend create svc error %d %+v", respBody.Code, respBody.Msg)
	}

	err = mapstructure.Decode(respBody.Data, &creatServiceRsp)
	if err != nil {
		return nil, err
	}

	logger.Infof("creat apflow service rsp: %+v", creatServiceRsp)
	return &creatServiceRsp, nil
}

func DeleteApflow(serviceId string, deviceType string) error {
	var respBody protocol.APISuccessRsp
	var client = &http.Client{
		Timeout: time.Second * 10,
	}

	path := APFLOW_URL + "/" + serviceId
	url := utils.GetHttpUrl(configs.Config.Relevant.Service.InferenceBackendSvc, path) + "?deviceType=" + deviceType
	logger.Infoln("del svc url: ", url)

	req, err := http.NewRequest("DELETE", url, nil)
	if err != nil {
		return err
	}

	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		return fmt.Errorf("inference-backend del svc error %d %+v", resp.StatusCode, resp.Body)
	}

	err = json.NewDecoder(resp.Body).Decode(&respBody)
	if err != nil {
		return err
	}

	if respBody.Code != 0 {
		return fmt.Errorf("inference-backend del svc error %d %+v", respBody.Code, respBody.Msg)
	}
	logger.Infoln("inference-backend delete ", serviceId, " response:", respBody)
	return nil
}
